<template>
  <div class='box-wrap'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'><Input v-model.trim="searchData.name" placeholder="请输入任务名称" clearable @on-enter="onSearchGetList()"></Input></div>      
        <div class='form-group-enquire'>
          <DatePicker type="daterange" placeholder="日期" style="width: 190px" :editable=false v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>
        </div>         
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" :stripe="stripe" border="none" :tableColumns="tableColumns" :tableData="list" :slotHeader="slotHeader" :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  @onPageChange="onChangePageSize" resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import bus from "@/commons/EventBus";
import {ACDN} from "@/commons/staticName";
export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      stripe:false,       
      value:true,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        page_size:30,
        page_index:1,
        start:"",
        end:"",        
        name:"",        
      },
      unique_id:"",
      versionsList:[{Id:-1,Name:'全部版本'},{Id:1,Name:'v1'},{Id:2,Name:'v2'}],
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      tableColumns:[
        {
          title: "序号",
          field: "id",
          align: 'center',
          slots:{
            default:({rowIndex,row},h) =>{
              return [h("div",this.searchData.page_size*(this.searchData.page_index-1)+(rowIndex+1))]
            }
          }
        },
        {
          title: "任务名称",
          field: "name",
          align: 'center',
        },
        {
          title: "任务类型",
          field: "task_type",
          align: 'center',
          slots: {
                default: ({row},h) => {
                  if (row.task_type==1) {
                    return [h("span","全球号码生成")]
                  }else if(row.task_type==2){
                    return [h("span","自定义号码生成")]
                  }
                }
            }           
        },
        {
          title: "数据总量",
          field: "generation_number_count",
          align: 'center',
        },
        {
          title: "可用数量",
          field: "nums_available",
          align: 'center',
        },
        {
          title: "去重数量",
          field: "nums_repetition",
          align: 'center',
        },
        {
          title: "国家",
          field: "country_name",
          align: 'center',
        },
        {
          title: "状态",
          field: "status",
          align: 'center',
          slots: {
                default: ({row},h) => {
                  if (row.status==1) {
                    return [h("span","进行中")]
                  }else if(row.status==2){
                    return [h("span","已完成")]
                  }else if(row.status==3){
                    return [h("span","未完成")]
                  }
                }
            }          
        },
        {
          title: "创建时间",
          field: "create_at",
          align: 'center',
          slots: {
            default: ({row},h) => {
              if(row.create_at <= 0){
                return [h("div","")]
              } else {
                 return [h("div",utils.dateFormat(row.create_at, "yyyy-MM-dd HH:mm:ss"))];
              }
            }
          }
        },
        {
          title: "操作",
          field: "action",        
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
                hButton.push(
                  h(
                    "el-button",
                    {
                      props: { type: "success", size: "small" },
                      style: { marginRight: "5px" },
                      on: {
                        click: () => {
                          this.downloadFile(row.unique_id,row.task_type);
                        }
                      }
                    },
                    "导出数据"
                  )
                );
              return hButton;
            });
            }
          }
        }        
      ],
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        this.initDate();
        this.onSearchGetList()
      }
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      //查询
      let res =  await this.RequestPost("queryTasks_list",this.searchData);//国家  
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) 
        this.list = res.data.list
        this.totalCnt = res.data.total
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },
    async editInfo(type,row) {
        
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "号码生成";
        info = {
        };
      }else{
        if (row.Status > 1){
          this.format.Status.labelDisabled = true
        }
        title = "编辑用户";
        info = {};
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
    },    
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      if (this.handleType==1) {
        actionName = 'createlask_item';
        tipText = '创建成功！';    
        postData = {};
      }else if(this.handleType==3){
        actionName = 'enable_item';
        tipText = '启用成功！';
        postData = {"id":postData.id};
      }else if(this.handleType==4){
        actionName = 'disable_item';
        tipText = '禁用成功！！';
        postData = {"id":postData.id};
      }
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        this.onSearchGetList();
        utils.showTip(tipText);
      }
      this.modal=true
      utils.hideLoading();
    },   
    onChangePageSize(page,pageSize){
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(){
      this.searchData.start = Date.parse(this.searchDate[0])/1000;
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400;
      this.onSearchGetList();
    },
    changeTime(val){
      if(val[0]!=""){
        this.searchTime = val;
      }else{
        this.searchTime = ['00:00','23:59'];
      }
      this.searchData.searchBeginDay = this.searchTime[0].split(":")[0]
      this.searchData.searchEndDay = this.searchTime[1].split(":")[0]
    },
    initDate(){
      let beginDay,endDay = ""
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    async downloadFile(item,typeid) {
      let res = await this.RequestPost("download_item",{"unique_id":item,"task_type":typeid});
        let downlo=ACDN + res.data
        //下载txt判断
          let index= res.data.lastIndexOf(".");//获取.的下标
          let ext = res.data.substr(index+1);//获取后缀txt
          let index2= res.data.lastIndexOf("/");//获取/的下标
          let ext2 = res.data.substr(index2+1,res.data.length);//获取/后的文件名
        if("txt".indexOf(ext.toLowerCase()) !== -1){
          this.exportData2(downlo,ext2)
        }else{
          window.open(ACDN+res.data)
        }      
    },     
    exportData2(url,name){
     const link = document.createElement("a");
      fetch(url)
      .then((res)=>res.blob())
      .then((blob)=>{
       link.href = URL.createObjectURL(blob)
       link.download = name
       document.body.appendChild(link)
       
       link.click()
        document.body.removeChild(link)
      })
     }     
  },
  mounted() {
    bus.$on('number',data =>{
        this.list=data
      })
  },
};
</script>  